<?php
/**
 * | @author 韩威兵^life <1877361302@qq.com>
 * +----------------------------------------------------------------------
 * | @copyright 2016 - 2019 HQ
 * +----------------------------------------------------------------------
 * | @version $Id: 2019/5/2 16:31 jiahe_new memberServer.php 韩威兵^life $
 * +----------------------------------------------------------------------
 */

namespace app\api\server\member;

use app\common\common\lib\OpensslEncrypt;
use app\common\common\model\member\member;
use app\common\common\model\order\fromId;
use app\common\common\model\oldModel\member\member as oldMember;
use app\common\common\model\oldModel\member\memberCard;
use app\common\common\model\oldModel\member\memberCardLog;
use app\common\common\Server\verifiableServer;

use app\api\server\storeServer;
use app\common\common\Server\commonServer;

class  memberServer {

    public $status = true;
    public $error = '';

    /**
     * 整理登录注册数据。
     * @return mixed
     */
    public function formatSignData(){
        $member['open_id']   = input('openid', '');
        $member['union_id']   = input('unionid', '');



        $member['nick_name'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', input('nick_name', ''));

        $member['phone'] = input('phone', '');
        $member['portrait'] = input('portrait', '');

        $member['province'] = input('province','');
        $member['city'] = input('city', '');
        $member['region'] = input('region', '');
        $member['sex'] = input('sex', 3);
        return $member;
    }


    /**
     * 添加formId
     * @param $member_id 新用户id
     * @param $open_id
     * @param $form_id
     * @return bool
     * @author 李鹏博^life <907215837@qq.com>
     */
    public function addUserNewFormId($member_id,$open_id,$form_id){

        $nowDate = date('Y-m-d H:i:s');

        $data = [
            'user_id' => $member_id,
            'open_id' => $open_id,
            'form_id' => $form_id,
            'create_time' => $nowDate,
            'expiration_time' => date('Y-m-d H:i:s',strtotime("$nowDate +1 week")),
        ];

        $fromId = new fromId();

        $result = $fromId->insertdata($data);
        if($result){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 创建或者修改用户信息
     * @param $member
     * @return bool
     */
    public function createUpdateMember($member){

        try{
            $member['last_login_ip'] = get_client_ip();
            $member['last_login_time'] = date('Y-m-d H:i:s');

            $member_model = new member();
            $where['open_id'] = $member['open_id'];
            $field = $member_model->findByWhere($where);
            //判断用户存在否，存在需要修改，但是，头像，昵称，省市区，不修改。
            if(empty($field)){
                aw_log($member,'member_log.log');
                $member_id = $member_model->insertMember($member);
                $field = $member;
                $field['id'] = $member_id;
                $field['status'] = 1;
                $field['is_new'] = 1;
            }else{
                unset($member['portrait']);
                unset($member['nick_name']);
                unset($member['province']);
                unset($member['city']);
                unset($member['region']);
                $update_res = $member_model->updateByOpenId($member['open_id'], $member);
                //修改失败，需要告知为什么失败
                if(!$update_res){
                    $error = $member_model->getError();
                    if(!empty($error)){
                        $this->status = false;
                        $this->error = '修改失败'.$error;
                        return false;
                    }
                }
                $old_member_model = new oldMember();
                $old_member_field = $old_member_model->findByWhere(['union_id'=>$field['union_id']]);
                if(empty($old_member_field)){
                    $field['is_new'] = 3;
                }else{
                    $field['is_new'] = 2;
                }
            }
            return $field;
        }catch (\Exception $e){
            $this->status = false;
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 加密用户信息
     * @param $info
     * @return string
     */
    public function encryptionMemberInfo($info){
        $info['time'] = time();
        $json_info = json_encode($info);
        return OpensslEncrypt::encrypt($json_info);
    }

    /**
     * 解密用户信息
     * @param $decrypt
     * @return mixed
     */
    public function decryptMemberInfo($decrypt){
        $json_info = OpensslEncrypt::decrypt($decrypt);
        return json_decode($json_info, true);
    }

    /**
     * 校验密钥
     * @param $ciphertext 密文
     * @param array $plaintext 需要校验的明文 ，可以为空
     * @return bool
     */
    public function checkCiphertext($ciphertext, $plaintext =[]){
        $info = $this->decryptMemberInfo($ciphertext);

        //密钥有效期为一天，超时则无效
        if(empty($info) || (time() - 86400) > $info['time']){
            return false;
        }
        //如果明文为空，无需校验
        if(empty($plaintext)){
            return $info;
        }
        foreach ($plaintext as $k=>$v){
            //如果明文跟密文不一致，则不合法
            if($info[$k] != $v){
                return false;
            }
        }
        return $info;
    }

    /**
     * 根据用户id，获取用户的早餐卡，和共享卡
     * @param $member_id
     * @return array
     */
    public function getBreakfastCard($member_id, $type = 0){
        $condition = [];
        $condition['member_id'] = $member_id;
        $condition['status'] = memberCard::$status_on;
        $condition['rest_times'] = ['gt', 0];
        $condition['time_end'] = ['gt', date('Y-m-d H:i:s')];
        if($type != 0){
            $condition['type'] = $type;
        }
        $member_card_model = new memberCard();
        $data = $member_card_model->allByWhere($condition);
        aw_log($data, 'member_card.log');
        return $data;
    }

    /**
     * 获取可以使用的早餐卡的列表
     * @param $card_data
     * @param $json_goods
     * @return array
     */
    public function getCanUseCar($card_data, $goods_num){

        foreach ($card_data as $k=>$v){
            if(($v['type'] == memberCard::$type_share) && ($v['rest_times'] < $goods_num)){
                unset($card_data[$k]);
            }elseif($v['type'] == memberCard::$type_alone){
                if($goods_num > 1){
                    unset($card_data[$k]);
                }else{
                    $log_where['card_id'] = $v['card_id'];
                    $log_where['create_time'] = ['gt',date("Y-m-d 00:00:00")];
                    $log_data = (new memberCardLog())->findByWhere($log_where);
                    if(!empty($log_data)){
                        unset($card_data[$k]);
                    }
                }
            }
        }
        return $card_data;
    }

    /**
     * 判断可以使用早餐卡吗，可以使用并返回早餐卡
     * @param $store_id
     * @param $classify_name
     * @param $member_info
     * @param $goods_id
     * @return array|int
     */
    public function isUseBreakfastCade($store_id, $classify_name, $member_info, $goods_num){
        $data = [];
        do{
            //旧平台用户不存在
            if(empty($member_info)){
                $code = 20003;
                break;
            }

            $store_server = new storeServer();
            //判断是否在早餐时间段
            $morning_status = $store_server->isMorning($store_id);
            if(!$morning_status){
                $code = 20000;
                break;
            }

            //判断是否是特殊粥料
            $classify_status = $store_server->isSpecialClassify($classify_name);
            if(!$classify_status){
                $code = 20001;
                break;
            }

            //拿出用户的正常的卡
            $card_data = $this->getBreakfastCard($member_info['member_id']);
            if(empty($card_data)){
                $code = 20002;
                break;
            }

            //判断共享卡和月卡能否使用
            $card_data = $this->getCanUseCar($card_data, $goods_num);
            if(empty($card_data)){
                $code = 20002;
                break;
            }

            $code = 0;
            $data = $card_data;

        }while(false);

        return ['code'=>$code, 'data'=>$data];
    }


    /**
     * 通过新用户的id，获取旧用户的信息
     * 先找unionid，然后才用手机号码获取用户
     * @param $new_mid
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    public function getOldMemberByNewId($new_mid){
        $new_member_field = (new member())->findByWhere(['id'=>$new_mid]);

        if(empty($new_member_field) || empty($new_member_field['union_id'])){
            return false;
        }
        $m_log['data'] = $new_member_field;
        $m_log['msg'] = '新用户信息';
        aw_log($m_log, 'member.log');
        $member_model = new oldMember();
        //通过UnionID 查找用户，
        $member_field = $member_model->findByWhere(['union_id'=> $new_member_field['union_id']]);
        $m_log['data'] = $member_field;
        $m_log['msg'] = '旧用户信息';
        aw_log($m_log, 'member.log');
        //如果不存在用手机号码兜底
        if(empty($member_field) && !empty($new_member_field['phone'])){
            $member_field = $member_model->findByWhere(['mobile'=>$new_member_field['phone']]);
        }

        if(empty($member_field)){
            return false;
        }
        $m_log['data'] = $member_field;
        $m_log['msg'] = '旧用户信息手机号';
        aw_log($m_log, 'member.log');
        return $member_field;
    }

    /**
     * 获取用户嘉和卡信息
     * @param $new_mid
     * @return bool
     */
    public function getMemberByCanxinjian($old_member){
        if($old_member === false){
            return false;
        }
        if(empty($old_member['jiahe_card'])){
            return false;
        }

        aw_log($old_member, 'canxingjian.log');
        $old_url = config('old_url');
        aw_log($old_url, 'canxingjian.log');
        $res_json = getcurl($old_url.'/home/Member/getMember?jiahe_card='.$old_member['jiahe_card']);
        $res_arr = json_decode($res_json, true);
        aw_log($res_arr, 'canxingjian.log');
        if($res_arr['code'] == 0){
            return $res_arr['data'];
        }
        return false;
    }


    /**
     * 增加用户金额消费
     * @param $member_id
     * @param int $money
     */
    public function addUserTotalCost( $member_id = 0 , $money = 0) {
        $member_model = new oldMember();
        return $member_model->where( array( 'member_id' => $member_id) )->setInc( 'total_cost' , $money);
    }





}  